jconed.toolbar.register_handler ( 'Link', function ( editor )
{
	var evt_name = 'post-exec-link';
	//set addEventListener only if hasn't been done yet
	if ( jconed._evts_list.indexOf ( evt_name ) == -1 )
	{
		jconed._evts_list.push ( evt_name );
		jconed.valid_events ( jconed._evts_list ); 
		jconed.addEventListener ( evt_name, function ( e )
		{
			var f = liwe.form.get ( 'jconed-link' );
			if ( ! f.get_value ( 'blank' ) ) return;
			var sel = jconed.editor.get_selection () [ 0 ];
			// HACK: works but it's not the best thing...
			if ( sel.startContainer.previousSibling && sel.startContainer.previousSibling.tagName.toLowerCase () == 'a' )
			{
				var link = sel.startContainer.previousSibling;
				link.target = '_blank';
				return;
			}
			//if first method doesn't work then parse startContainer and compare url in anchor tags
			var i, els = sel.startContainer.getElementsByTagName ( 'a' );
			for  ( i = 0; i < els.length; i ++ )
			{
				if ( els [ i ].href.indexOf ( e.params.value ) != -1 )
				{
					els [ i ].setAttribute ( 'target', '_blank' );
					break;
				}
			}
		} );
	}
	
	var f = new liwe.form.instance ( 'jconed-link', 'no-action' );
	f.text ( { label: 'URL', name: 'link', size: 30 } );
	f.checkbox ( { label: 'Pagina nuova', name: 'blank', value: '_blank' } );
	f.submit ( 'Update' );
	f.events [ 'submit' ] = function ()
	{
		var link = f.get_value ( 'link' );
		jconed.execute ( 'createLink', link, evt_name );
		return false;
	};
	jconed.toolbar.set_context ( f.get () );
} );

jconed.toolbar.register_handler ( 'Unlink', function ( editor )
{
	jconed.execute ( 'unlink' );
} );
